package com.scitc.pleasurevideo;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.scitc.pleasurevideo.adapter.CategoryRecyclerViewAdapter;
import com.scitc.pleasurevideo.adapter.RefreshListAdapter;
import com.scitc.pleasurevideo.data.DataUtil;
import com.scitc.pleasurevideo.data.StaticDataMan;
import com.scitc.pleasurevideo.helper.ForwardHelper;
import com.scitc.pleasurevideo.pojo.DoubanTvVo;
import com.scitc.pleasurevideo.util.OnClickUtil;
import com.scitc.pleasurevideo.util.UrlUtil;

import java.util.ArrayList;
import java.util.List;

import static com.scitc.pleasurevideo.Tabhome.chingeAppbarLayout;

/**
 * @author 853
 */
public class CategoryFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
    private Context mcontext;
    private List<String> items = new ArrayList<>();
    private RecyclerView rvTagsCategoryHor;
    private CategoryRecyclerViewAdapter mTagAdapter;
    private RecyclerView tvGenresCategoryHor;
    private CategoryRecyclerViewAdapter mGenresAdapter;
    private RecyclerView tvCountriesCategoryHor;
    private CategoryRecyclerViewAdapter mCountriesAdapter;
    private RecyclerView tvYearRangeCategoryHor;
    private CategoryRecyclerViewAdapter mYearAdapter;

    private static String tagsString = "全部";
    private static String genresString = "全部";
    private static String countriesString = "全部";
    private static String yearRangeString = "全部";


    private RecyclerView recyclerView;
    private SwipeRefreshLayout swipeRefreshLayout;
    private static String sortTextString = "U";
    private static int page_now = 0;
    private static int number = 0;
    private static String URL;


    private RefreshListAdapter refreshListAdapter;
    private List<DoubanTvVo> doubanTvPojoList = new ArrayList<>();
    private RelativeLayout searchBar;

    static CategoryFragment newInstance() {
        Bundle args = new Bundle();
        CategoryFragment fragment = new CategoryFragment();
        fragment.setArguments(args);
        return fragment;
    }

    private boolean isHaveMoreData = true;
    private boolean loading = false;
    private LinearLayoutManager layoutManager;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View view = inflater.inflate(R.layout.fragment_category, container, false);
        initView(view);
        loadData();
        onClick();
        initListView();
        refreshListMoreLoad();
        return view;
    }

    /**
     * 点击事件
     */
    private void onClick() {
        //第一个分类的点击事件
        mTagAdapter.setOnClickItemListener(position -> {
            mTagAdapter.setPosition(position);
            tagsString = StaticDataMan.tagsCategoryArray[position];
            onRefresh();
//            initListView();
        });
        //第二个分类的点击事件
        mGenresAdapter.setOnClickItemListener(position -> {
            mGenresAdapter.setPosition(position);
            genresString = StaticDataMan.genresCategoryArray[position];
            onRefresh();
//            initListView();
        });
        //第三个分类的点击事件
        mCountriesAdapter.setOnClickItemListener(position -> {
            mCountriesAdapter.setPosition(position);
            countriesString = StaticDataMan.countriesCategoryArray[position];
            onRefresh();
//            initListView();
        });
        //第四个分类的点击事件
        mYearAdapter.setOnClickItemListener(position -> {
            mYearAdapter.setPosition(position);
            yearRangeString = StaticDataMan.yearRangeCategoryArray[position];
            onRefresh();
//            initListView();
        });
        //列表的点击事件
        refreshListAdapter.setOnClickItem(position -> {
            DoubanTvVo doubanTvPojo = refreshListAdapter.getItemPosiion(position);
            ForwardHelper.toTvMenuContentActivity((Activity) mcontext, doubanTvPojo);
        });
        //搜索bar的点击事件
        searchBar.setOnClickListener(view -> {
            OnClickUtil.setViewClickTimes(searchBar);
            ForwardHelper.toSearchActivity((Activity) mcontext);
        });
        //返回列表顶部的按钮 点击事件
//        igCategoryUp.setOnClickListener(view -> recyclerView.post(() -> recyclerView.smoothScrollToPosition(0)));

    }

    /**
     * 加载数据，加载头部分类的数据
     */
    private void loadData() {
        List<String> tagsList = DataUtil.array_list(StaticDataMan.tagsCategoryArray);
        mTagAdapter.addAllItems(tagsList);
        List<String> genresList = DataUtil.array_list(StaticDataMan.genresCategoryArray);
        mGenresAdapter.addAllItems(genresList);
        List<String> countriesList = DataUtil.array_list(StaticDataMan.countriesCategoryArray);
        mCountriesAdapter.addAllItems(countriesList);
        List<String> yearRangeList = DataUtil.array_list(StaticDataMan.yearRangeCategoryArray);
        mYearAdapter.addAllItems(yearRangeList);
    }

    /**
     * 初始化控件，以及初始化addpter
     * @param view
     */
    private void initView(View view) {
        mcontext = getContext();

        mTagAdapter = new CategoryRecyclerViewAdapter(getContext(), getItems());
        rvTagsCategoryHor = view.findViewById(R.id.rvTagsCategoryHor);
        rvTagsCategoryHor.setAdapter(mTagAdapter);
        rvTagsCategoryHor.setNestedScrollingEnabled(false);

        mGenresAdapter = new CategoryRecyclerViewAdapter(getContext(), getItems());
        tvGenresCategoryHor = view.findViewById(R.id.tvGenresCategoryHor);
        tvGenresCategoryHor.setAdapter(mGenresAdapter);
        tvGenresCategoryHor.setNestedScrollingEnabled(false);

        mCountriesAdapter = new CategoryRecyclerViewAdapter(getContext(), getItems());
        tvCountriesCategoryHor = view.findViewById(R.id.tvCountriesCategoryHor);
        tvCountriesCategoryHor.setAdapter(mCountriesAdapter);
        tvCountriesCategoryHor.setNestedScrollingEnabled(false);

        mYearAdapter = new CategoryRecyclerViewAdapter(getContext(), getItems());
        tvYearRangeCategoryHor = view.findViewById(R.id.tvYearRangeCategoryHor);
        tvYearRangeCategoryHor.setAdapter(mYearAdapter);
        tvYearRangeCategoryHor.setNestedScrollingEnabled(false);

//        igCategoryUp = view.findViewById(R.id.igCategoryUp);
        searchBar = view.findViewById(R.id.rl_query);
        refreshListAdapter = new RefreshListAdapter(mcontext, doubanTvPojoList);
        recyclerView = view.findViewById(R.id.mListView);
        layoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(refreshListAdapter);

        swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipeRefreshLayout);
        swipeRefreshLayout.setOnRefreshListener(this);
        swipeRefreshLayout.setColorSchemeResources(R.color.main_color,
                android.R.color.holo_red_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_dark);
    }

    /**
     * 对item 进行 重置 返回
     * @return
     */
    @SuppressWarnings("unchecked")
    private List<String> getItems() {
        return (List<String>) ((ArrayList) items).clone();
    }

    /**
     * 初始化list数据
     */
    private void initListView() {
        URL = setUrlString();
        page_now = 0;
        number = 0;
        loading=false;
        isHaveMoreData=true;
        OKgo(0);
    }

    /**
     * 设置URL地址 缺少 从第几个开始 start= 的值
     *
     * @return url 地址
     */
    private String setUrlString() {
        //sort是排序类型
        //range是分数区间，默认是0-10全选
        //https://movie.douban.com/j/new_search_subjects?sort=U&range=0,10&start=0
        StringBuffer urlstring = new StringBuffer();
        urlstring.append(UrlUtil.api_string).append(UrlUtil.url_path);
        urlstring.append("sort=").append(sortTextString);
        urlstring.append("&range=0,10");

        if (!(tagsString.equals(StaticDataMan.tagsCategoryArray[0]))) {
            urlstring.append("&tags=").append(tagsString);
        }
        if (!(genresString.equals(StaticDataMan.genresCategoryArray[0]))) {
            urlstring.append("&genres=").append(genresString);
        }
        if (!(countriesString.equals(StaticDataMan.countriesCategoryArray[0]))) {
            urlstring.append("&countries=").append(countriesString);
        }
        if (!(yearRangeString.equals(StaticDataMan.yearRangeCategoryArray[0]))) {
            urlstring.append("&year_range=").append(yearRangeString);
        }
        urlstring.append("&start=");

        return urlstring.toString();
    }

    /**
     * 初始化数据的
     */
    private void OKgo(final int start) {
        String url = URL + start;
        OkGo.<String>get(url)
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        List<DoubanTvVo> doubanTvPojos = user_fromJSON(response.body());
                        if (doubanTvPojos == null || doubanTvPojos.size() < 1) {
                            return;
                        }
                        if (start > 0) {
                            refreshListAdapter.addItems(doubanTvPojos);
                        } else {
                            refreshListAdapter.resetItems(doubanTvPojos);
                            number = doubanTvPojos.size();
                        }
                        recyclerView.postInvalidate();

                    }
                });
    }

    /**
     * 将json 转换为list
     * @param source
     * @return
     */
    private List<DoubanTvVo> user_fromJSON(String source) {
        try {
            Gson gson = new Gson();

            String s = source.replace("{\"data\":[", "[");
            String ss = s.replace("]}", "]");

            List<DoubanTvVo> doubanTvPojos = gson.fromJson(ss, new TypeToken<List<DoubanTvVo>>() {
            }.getType());
            return doubanTvPojos;
        } catch (Exception e) {
            return null;
        }
    }



    /**
     * 列表的滑动事件的监听
     * 主要是上拉加载更多
     */
    private void refreshListMoreLoad() {
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                chingeAppbarLayout.OnChingeAppbarLayout(1);
                if (dy > 0) //向下滚动
                {
                    if (isHaveMoreData) //向下滚动
                    {
                        int visibleItemCount = layoutManager.getChildCount();
                        int totalItemCount = layoutManager.getItemCount();
                        int pastVisiblesItems = layoutManager.findFirstVisibleItemPosition();

                        if (!loading && (visibleItemCount + pastVisiblesItems) >= totalItemCount) {
                            loading = true;
                            refreshListAdapter.setLoadingDataFooterViewUi();
                            onMoreLoad();
                        }
                    }
                }
            }
        });
    }

    /**
     * 加载更多数据
     */
    private void onMoreLoad() {
        loading=true;
        page_now++;
        final int page = page_now * number;
        String url = URL + page;
        OkGo.<String>get(url)
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        List<DoubanTvVo> doubanTvPojos = user_fromJSON(response.body());
                        loading=false;
                        if (doubanTvPojos == null || doubanTvPojos.size() < 1) {
                            isHaveMoreData=false;
                            refreshListAdapter.setNoDataFooterViewUI();
                            return;
                        }
                        refreshListAdapter.setHaveDataFooterViewUI();
                        isHaveMoreData=true;
                        if (page > 0) {
                            refreshListAdapter.addItems(doubanTvPojos);
                        } else {
                            refreshListAdapter.resetItems(doubanTvPojos);
                            number = doubanTvPojos.size();
                        }

                    }
                });
    }

    /**
     * 下拉刷新
     */
    @Override
    public void onRefresh() {
        URL = setUrlString();
        loading=true;
        isHaveMoreData=true;
        page_now = 0;
        number = 0;
        String url = URL + 0;
        OkGo.<String>get(url)
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        List<DoubanTvVo> doubanTvPojos = user_fromJSON(response.body());
                        if (!(doubanTvPojos == null || doubanTvPojos.size() < 1)) {
                            refreshListAdapter.resetItems(doubanTvPojos);
                            number = doubanTvPojos.size();
                            isHaveMoreData=true;
                        }else {
                            refreshListAdapter.setNoDataFooterViewUI();
                            isHaveMoreData=false;
                        }
                        refreshListAdapter.setHaveDataFooterViewUI();
                        loading=false;
                        swipeRefreshLayout.setRefreshing(false);
                        Toast.makeText(mcontext, "刷新成功", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    /**
     * 进入这个界面也要回调函数，设置状态栏是白底黑字
     */
    @Override
    public void onResume() {
        super.onResume();
        chingeAppbarLayout.OnChingeAppbarLayout(1);
    }
}
